<script setup lang="ts">
import { ElMessage, type UploadFile, type UploadFiles } from "element-plus";
import { onMounted, ref } from "vue";
import Selector from "./Selector.vue";

/**
 * 外层div
 */
const rufflePlayerDom = ref<HTMLDivElement | null>(null);

/**
 * 当前使用的文件
 */
const fileRef = ref<File | null>(null);

/**
 * ruffle player的对象
 */
const playerInstance = ref<any>(null);

/**
 * 当前选择的游戏
 */
const gameUrl = ref<string>("");

class RufflePlayer {
  newest = () => {
    return {
      createPlayer: (): any => {
        return {};
      },
    };
  };
}
const getRufflePlayer = () => {
  if (!("RufflePlayer" in window)) {
    return null;
  }
  return window.RufflePlayer as RufflePlayer;
};

const handleFileChange = (
  uploadFile: UploadFile,
  _uploadFiles: UploadFiles
) => {
  const file = uploadFile.raw;
  if (!file) return;

  fileRef.value = file;
};

const ruffleLoad = (url: string) => {
  if (!rufflePlayerDom.value) return;
  const rufflePlayer = getRufflePlayer();
  if (!rufflePlayer) {
    return;
  }
  rufflePlayerDom.value.innerHTML = "";

  const ruffle = rufflePlayer.newest();
  const player = ruffle.createPlayer();
  playerInstance.value = player;
  rufflePlayerDom.value.appendChild(player);
  player.ruffle().load({
    url,
    ...{
      autoplay: "on",
      allowFullscreen: false,
      forceScale: true,
      letterbox: "on",
      scale: "showAll",
      forceAlign: true,
    },
  });
};

const onClickLoad = () => {
  if (!fileRef.value) return;

  const url = URL.createObjectURL(fileRef.value);
  ElMessage.info(`正在加载：${fileRef.value.name}`);
  ruffleLoad(url);
  onClickResize();
};

const onClickLoadSelect = () => {
  if (!gameUrl.value) {
    ElMessage.error("请选择文件");
    return;
  }

  ElMessage.info(`正在加载：${gameUrl.value}`);
  ruffleLoad(gameUrl.value);
  onClickResize();
};

// 动态调整大小的方法也需要更新
const resizePlayer = (width: number, height: number) => {
  if (!playerInstance.value) return;
  playerInstance.value.style.width = `${width}px`;
  playerInstance.value.style.height = `${height}px`;
};

const onClickResize = () => {
  if (!rufflePlayerDom.value) return;
  const domRect = rufflePlayerDom.value.getBoundingClientRect();
  const { width, height } = domRect;
  resizePlayer(width, height);
};

const onClickTest = () => {
  if (!playerInstance.value) return;

  // try {
  //   // 获取 shadow root 内的 canvas
  //   const shadowRoot = playerInstance.value.shadowRoot;
  //   const canvas = shadowRoot?.querySelector("canvas");
  //   console.log("canvas", playerInstance.value, shadowRoot, canvas);

  //   if (canvas && shadowRoot) {
  //     console.log("找到 canvas 元素");

  //     const triggerDom = shadowRoot

  //     setTimeout(() => {
  //       console.log("press");

  //       const mouseDownEvent = new MouseEvent("mousedown", {
  //         button: 2, // 2 represents right button
  //         bubbles: true,
  //         cancelable: true,
  //       });
  //       triggerDom.dispatchEvent(mouseDownEvent);

  //       setTimeout(() => {
  //         const mouseUpEvent = new MouseEvent("mouseup", {
  //           button: 2,
  //           bubbles: true,
  //           cancelable: true,
  //         });
  //         triggerDom.dispatchEvent(mouseUpEvent);
  //       }, 100);
  //     }, 1000);
  //   }
  // } catch (error) {
  //   console.error("发送按键信号失败:", error);
  // }
};

onMounted(() => {});
</script>

<template>
  <div
    class="flex flex-1 flex-col justify-start items-start bg-gray-100 overflow-hidden"
  >
    <div class="flex w-full box-border p-2 items-center justify-center">
      <div class="flex flex-row bg-white rounded">
        <p v-if="fileRef" class="mx-3 leading-8">
          {{ fileRef && fileRef.name }}
        </p>
        <div class="">
          <el-upload
            :auto-upload="false"
            accept=".swf"
            :show-file-list="false"
            :on-change="handleFileChange"
          >
            <el-button type="primary">选择自定义文件</el-button>
          </el-upload>
        </div>
        <el-button type="primary" plain @click="onClickLoad"
          >加载自定义文件</el-button
        >
      </div>

      <div class="flex flex-row bg-white rounded mx-3">
        <Selector v-model="gameUrl" />
        <el-button type="primary" plain @click="onClickLoadSelect"
          >加载选择的文件</el-button
        >
      </div>
      <el-button type="primary" plain @click="onClickResize"
        >重置大小</el-button
      >
      <el-button type="primary" plain @click="onClickTest">测试按钮</el-button>
    </div>

    <div
      class="flex-1 w-full flex flex-col justify-center items-center overflow-hidden"
      ref="rufflePlayerDom"
    >
      <div class="flex flex-col">
        <div class="my-0 mx-auto">
          <el-upload
            :auto-upload="false"
            accept=".swf"
            :show-file-list="false"
            :on-change="handleFileChange"
          >
            <el-button type="primary">选择自定义文件</el-button>
          </el-upload>
        </div>
        <el-empty description="还未加载" />
      </div>
    </div>
  </div>
</template>
